import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/useStore';

class HttpClient {
  private instance: AxiosInstance;

  constructor(baseURL: string, timeout = 10000) {
    this.instance = axios.create({
      baseURL,
      timeout,
    });

    // 请求拦截器：自动附带 token
    this.instance.interceptors.request.use(
      (config) => {
        // 添加通用的请求配置，比如添加 Token
        const userStore = useUserStore();
        const authToken = userStore.getAuthToken();
        if (authToken) {
          config.headers.Authorization = `${authToken}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
        // 可以在这里统一处理响应数据
        if (response.data.code === 1001) {
          // showToast({ type: 'fail', message: response.data?.errorMsg || '请求失败', duration: 3000 });
          ElMessage.error(response.data?.errorMsg || '请求失败');
          throw new Error(response.data?.errorMsg || '请求失败');
        }
        if (response.data.code === 1000) {
          this.toLoginPage();
          throw new Error(response.data?.errorMsg || '请求失败');
        }
        return response;
      },
      (error) => {
        // 统一处理错误
        const data = error.response?.data;
        if (data?.code === 403) {
          this.toLoginPage();
        } else {
          // showToast(data?.msg || '请求失败');
          showToast({ type: 'fail', message: data?.msg || '请求失败', duration: 3000 });
          throw new Error(data?.msg || '请求失败');
          // return Promise.reject(error);
        }
      }
    );
  }

  public toLoginPage() {
    const userStore = useUserStore();
    const pathname = window.location.pathname;
    const isAdmin = window.location.href.includes('/admin') || window.location.href.includes('/login');
    if (isAdmin) {
      userStore.userLogout();
      window.location.replace(`${pathname}#/admin/login`);
      // router.default.replace({ name: 'AdminLogin'});
    } else {
      userStore.userLogout();
      window.location.replace(`${pathname}#/landing`);
    }
  }

  // GET 方法
  public async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response: AxiosResponse<T> = await this.instance.get(url, config);
    return response?.data;
  }

  // POST 方法
  public async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const response: AxiosResponse<T> = await this.instance.post(url, data, config);
    return response?.data;
  }

  public async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response: AxiosResponse<T> = await this.instance.delete(url, config);
    return response?.data;
  }

  // 上传文件方法
  public async uploadFile<T>(url: string, file: File, fileKey: string, config?: AxiosRequestConfig): Promise<T> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('fileKey', fileKey);

    const response: AxiosResponse<T> = await this.instance.post(url, formData, {
      ...config,
      headers: {
        ...config?.headers,
        // 注意：axios 会自动设置 multipart/form-data 的请求头，这里无需手动设置
      },
    });

    return response?.data;
  }
}

const http = new HttpClient('/api');

export default http;